import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../domain/services/directory_service.dart';
import '../../../data/api/directories_api.dart';
import '../../../data/models/directory.dart' as dir;
import '../../widgets/file_explorer/path_navigation_bar.dart';
import '../../widgets/file_explorer/filter_tabs.dart';
import '../../widgets/file_explorer/file_explorer_view.dart';
import '../../widgets/file_explorer/filtered_files_view.dart';
import '../../widgets/file_explorer/bottom_action_bar.dart';
import '../../widgets/common/loading_view.dart';
import '../../widgets/common/error_view.dart';
import '../../widgets/dialogs/input_dialog.dart';
import '../../widgets/dialogs/confirm_dialog.dart';
import '../upload/upload_screen.dart';

/// 文件浏览屏幕
class FilesScreen extends StatefulWidget {
  const FilesScreen({Key? key}) : super(key: key);

  @override
  State<FilesScreen> createState() => _FilesScreenState();
}

class _FilesScreenState extends State<FilesScreen> {
  // 当前选中的标签索引
  int _currentTabIndex = 0;

  @override
  void initState() {
    super.initState();
    // 初始化时加载根目录
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadRootDirectory();
    });
  }

  // 加载根目录数据
  Future<void> _loadRootDirectory() async {
    final directoryService = Provider.of<DirectoryService>(
      context,
      listen: false,
    );
    await directoryService.loadRootDirectory();
  }

  @override
  Widget build(BuildContext context) {
    final directoryService = Provider.of<DirectoryService>(context);

    // 显示加载中状态
    if (directoryService.isLoading) {
      return const LoadingView();
    }

    // 显示错误状态
    if (directoryService.errorMessage != null) {
      return ErrorView(
        errorMessage: directoryService.errorMessage!,
        onRetry: _loadRootDirectory,
      );
    }

    return Column(
      children: [
        // 目录路径导航栏
        PathNavigationBar(
          pathHistory: directoryService.directoryPathHistory,
          onNavigate: directoryService.navigateToDirectory,
          onNavigateToParent: directoryService.navigateToParentDirectory,
          onSearch: _handleSearch,
        ),

        // 文件类型筛选标签
        FilterTabs(
          currentIndex: _currentTabIndex,
          onTabChanged: (index) => setState(() => _currentTabIndex = index),
        ),

        // 文件列表
        Expanded(
          child:
              _currentTabIndex == 0
                  ? FileExplorerView(
                    directoryService: directoryService,
                    onFileTap: _handleFileTap,
                    onFileMenuAction: _handleFileMenuAction,
                    onDirectoryMenuAction: _handleDirectoryMenuAction,
                  )
                  : FilteredFilesView(
                    directoryService: directoryService,
                    filterIndex: _currentTabIndex,
                    onFileTap: _handleFileTap,
                    onFileMenuAction: _handleFileMenuAction,
                  ),
        ),

        // 底部操作栏
        BottomActionBar(
          onUpload: _handleUpload,
          onCreateFolder: _handleCreateFolder,
          onSort: _handleSort,
        ),
      ],
    );
  }

  /// 处理搜索
  void _handleSearch() {
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('搜索功能即将推出')));
  }

  /// 处理上传
  void _handleUpload() {
    Navigator.of(
      context,
    ).push(MaterialPageRoute(builder: (context) => const UploadScreen()));
  }

  /// 处理排序
  void _handleSort() {
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('排序功能即将推出')));
  }

  /// 处理创建文件夹
  void _handleCreateFolder() {
    final directoryService = Provider.of<DirectoryService>(
      context,
      listen: false,
    );

    InputDialog.show(
      context: context,
      title: '新建文件夹',
      hint: '输入文件夹名称',
      validator: (value) {
        if (value.trim().isEmpty) {
          return '文件夹名称不能为空';
        }
        return null;
      },
      onConfirm: (name) {
        if (name.trim().isNotEmpty) {
          directoryService.createDirectory(name.trim());
        }
      },
    );
  }

  /// 处理文件点击
  void _handleFileTap(FileItem file) {
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(SnackBar(content: Text('预览 ${file.fileName} 功能即将推出')));
  }

  /// 处理文件菜单操作
  void _handleFileMenuAction(String action, FileItem file) {
    final directoryService = Provider.of<DirectoryService>(
      context,
      listen: false,
    );

    switch (action) {
      case 'delete':
        ConfirmDialog.show(
          context: context,
          title: '删除文件',
          content: '确定要删除文件 "${file.fileName}" 吗？',
          confirmText: '删除',
          confirmColor: Colors.red,
          onConfirm: () => directoryService.deleteFile(file.id),
        );
        break;
      case 'download':
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('下载文件功能即将推出')));
        break;
      case 'share':
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('分享文件功能即将推出')));
        break;
      case 'rename':
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('文件重命名功能即将推出')));
        break;
    }
  }

  /// 处理目录菜单操作
  void _handleDirectoryMenuAction(String action, dir.Directory directory) {
    final directoryService = Provider.of<DirectoryService>(
      context,
      listen: false,
    );

    switch (action) {
      case 'rename':
        InputDialog.show(
          context: context,
          title: '重命名文件夹',
          hint: '输入新的文件夹名称',
          initialValue: directory.name,
          validator: (value) {
            if (value.trim().isEmpty) {
              return '文件夹名称不能为空';
            }
            return null;
          },
          onConfirm: (name) {
            if (name.trim().isNotEmpty && name.trim() != directory.name) {
              directoryService.renameDirectory(directory.id, name.trim());
            }
          },
        );
        break;
      case 'delete':
        ConfirmDialog.show(
          context: context,
          title: '删除文件夹',
          content: '确定要删除文件夹 "${directory.name}" 吗？这将删除其中的所有文件和子文件夹。',
          confirmText: '删除',
          confirmColor: Colors.red,
          onConfirm: () => directoryService.deleteDirectory(directory.id),
        );
        break;
      case 'share':
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('分享文件夹功能即将推出')));
        break;
    }
  }
}
